<template>
  <div class="flex-column">
    <div class="flex justify-between">
      <div class="flex">
        <el-button v-if="permission.addBtn" type="primary" icon="el-icon-plus" @click="add">{{
          $t('ADD')
        }}</el-button>
      </div>
      <div class="flex flex-wrap">
        <el-select
          ref="orgSelect"
          v-model="param.orgId"
          style="width: 300px"
          class="ml-10 mb-10"
          :placeholder="$t('PLEASE_SELECT_ORG')"
          clearable
          popper-class="select-tree"
          @clear="orgClear"
        >
          <el-option class="tree-option" :label="param.orgName" :value="param.orgId">
            <el-tree :data="orgTree" accordion @node-click="orgTreeClick" />
          </el-option>
        </el-select>
        <el-input
          v-model.trim="param.keyword"
          maxlength="32"
          style="width: 300px"
          clearable
          class="ml-10 mb-10"
          :placeholder="`${$t('USER_NUM')}/${$t('REAL_NAME')}`"
          @change="search"
          @keyup.enter.native="$debounce(search)"
        />
        <el-button type="primary" class="ml-10 mb-10" @click="$debounce(search)">{{
          $t('QUERY')
        }}</el-button>
      </div>
    </div>
    <TableView
      :table-header="tableHeader"
      :table-data="tableData"
      :page-data="pageData"
      :operate-width="permission.pwd ? 200 :150"
      @operate="operate"
      @pageChange="pageChange"
    />
    <edit
      :visible="editShow"
      :type="operateType"
      :data="row"
      :org-tree="orgTree"
      :base-role-list="roleList"
      @close="close"
    />
  </div>
</template>

<script>
  import { mapGetters } from 'vuex'
  import UserApi from '@/api/system/UserApi'
  import OrgApi from '@/api/system/OrgApi'
  import RoleApi from '@/api/system/RoleApi'
  import Edit from './Edit'
  import TableView from '@/components/TableView'
  let searchData = {} // 查询参数 只有点了查询有效
  export default {
    name: 'SystemUser',
    components: { Edit, TableView },
    data() {
      return {
        tableData: [],
        orgTree: [],
        roleList: [],
        orgId: null,
        orgName: null,
        param: {
          orgId: '',
          keyword: ''
        },
        pageData: {
          page: 1,
          size: 20,
          total: 0
        },
        row: {},
        operateType: 'add',
        editShow: false,
        tableHeader: [
          {
            label: 'USER_NUM',
            prop: 'userId',
            fixed: 'left',
            configType: 'default'
          },
          {
            label: 'REAL_NAME',
            prop: 'realName'
          },
          {
            label: 'AFFILIATION',
            prop: 'orgName'
          },
          {
            label: 'ROLE',
            prop: 'roleName'
          },
          {
            label: 'GENDER',
            prop: 'gender',
            configType: 'extend'
          },
          {
            label: 'BIRTHDAY',
            prop: 'birthday',
            configType: 'extend'
          },
          {
            label: 'MOBILE',
            prop: 'phone',
            configType: 'extend'
          },
          {
            label: 'CONTACTADDRESS',
            prop: 'address',
            configType: 'extend'
          },
          {
            label: 'EMAIL',
            prop: 'email',
            configType: 'extend'
          },
          {
            label: 'WHETHER_ENABLE',
            prop: 'enableName'
          }
        ]
      }
    },
    computed: {
      ...mapGetters(['regionTree', 'getOrg', 'getLocale', 'getUser', 'getRoles']),
      permission() {
        return this.$store.getters.getAuthData('sys:user')
      }
    },
    created() {
      if (this.getOrg.orgType !== 'PLATFORM') {
        this.orgId = this.getOrg.orgId
        this.param.orgId = this.orgId
      }
      searchData = {
        ...this.param
      }
      this.getAll()
    },
    methods: {
      getAll() {
        Promise.all([OrgApi.tree(this.orgId), RoleApi.list(), this.loadData(true)]).then(
          ([res1, res2, res3]) => {
            this.orgTree = res1 || []
            if (this.orgId) {
              this.orgName = this.$findName(this.orgId, this.orgTree, 'orgId', 'orgName')
              this.param.orgName = this.orgName
            }
            this.roleList = res2 || []
            this.formateData(res3)
          }
        ).catch(err => {
          console.log(err)
        })
      },
      async loadData(isPromise) {
        const param = {
          ...searchData,
          ...this.pageData
        }
        const result = await UserApi.page(param)
        if (isPromise) {
          return result
        } else {
          this.formateData(result)
        }
      },
      formateData(result) {
        const list = result.list || []
        this.tableData = list.map(i => {
          return {
            ...i,
            btns: this.getBtns(i),
            orgName: this.$findName(i.orgId, this.orgTree, 'orgId', 'orgName'),
            roleName: this.$findName(i.roleId, this.roleList, 'roleId', 'roleName'),
            enableName: i.enable ? this.$t('ENABLE') : this.$t('DISABLE')
          }
        })
        this.pageData.total = result.total
      },
      getBtns(row) {
        const btns = [
          {
            key: 'view',
            show: true,
            label: 'VIEW'
          },
          {
            key: 'mod',
            show: this.modAuth(row),
            label: 'MOD'
          },
          {
            key: 'resetPwd',
            show: this.resetPwdAuth(row),
            label: 'RESET_PASSWORD'
          },
          {
            key: 'del',
            show: this.delAuth(row),
            label: 'DEL'
          }
        ]
        return btns.filter(i => i.show)
      },
      operate(data) {
        switch (data.type) {
        case 'view':
          this.operateType = 'view'
          this.row = data.data
          this.editShow = true
          break
        case 'mod':
          this.operateType = 'mod'
          this.row = data.data
          this.editShow = true
          break
        case 'resetPwd':
          this.resetPwd(data.data)
          break
        case 'del':
          this.del(data.data)
          break
        }
      },
      search() {
        this.pageData.page = 1
        searchData = {
          ...this.param
        }
        this.loadData()
      },
      pageChange(data) {
        this.pageData = data
        this.loadData()
      },
      orgTreeClick(node) {
        this.param.orgId = node.orgId
        this.param.orgName = node.orgName
        this.$refs.orgSelect.blur()
        this.search()
      },
      orgClear() {
        this.param.orgId = this.orgId
        this.param.orgName = this.orgName
        this.search()
      },
      add() {
        this.operateType = 'add'
        this.row = {}
        this.editShow = true
      },
      del(row) {
        this.$confirm(this.$t('CONFIRM_DELETION_PROMPT_TIP', { key: this.$t('USER'), value: row.userId }), { type: 'warning' })
          .then(() => {
            UserApi.del(row.id, { userId: row.userId, realName: row.realName }).then(result => {
              if (result) {
                this.$message.success(this.$t('DELETE_SUCCESS'))
                this.loadData()
              }
            })
          })
          .catch(() => {})
      },
      resetPwd(row) {
        this.$confirm(this.$t('RESETPASSWORD') + '?', { type: 'warning' })
          .then(() => {
            UserApi.resetPwd(row).then(result => {
              if (result) {
                this.$message.success(this.$t('RESET_SUCCESSFULLY') + '！')
              }
            })
          })
          .catch(() => {})
      },
      close(load) {
        this.editShow = false
        if (load === true) {
          this.loadData()
        }
      },
      resetPwdAuth(row) {
        let canReset = true
        /**
         * 系统管理员可重置所有用户的密码
         * 交付者角色的用户可以重置除系统管理员以外角色的用户的密码
         * 管理者角色的用户不能重置系统管理员和交付者角色的用户的密码
         */
        const currentRole = window.__config__.roleLevel.find(i => i.id === this.getRoles[0]) || ''
        const currentRowRole = window.__config__.roleLevel.find(i => i.id === row.roleId) || ''
        if (currentRowRole) {
          if (currentRole.level <= currentRowRole.level) {
            canReset = true
          } else {
            canReset = currentRowRole.level === 4
          }
        }
        return this.permission.pwd && row.userId !== 'admin' && canReset
      },
      modAuth(row) {
        let canMod = true
        // 当前登录用户可删除同属一个机构下的其它用户
        // const currentOrgId = this.getUser.orgId
        // const currentRowOrgId = row.orgId
        // const parentList = (getParentsById(this.orgTree, currentRowOrgId, 'key') || [])
        //   .map(i => i.key)
        //   .reverse()
        // if (parentList.includes(currentOrgId) || this.getUser.userId === 'admin') {
        //   canMod = true
        // } else {
        //   canMod = false
        // }
        // user_jf只能被系统管理员修改
        if (row.userId.toLowerCase() === 'user_jf') {
          canMod = this.getUser.userId === 'admin'
        }
        // user_gl只能被系统管理员和交付角色的用户修改
        if (row.userId.toLowerCase() === 'user_gl') {
          canMod = this.getUser.userId === 'admin' || this.getUser.userId === 'delivery'
        }
        return this.permission.mod && canMod
      },
      delAuth(row) {
        // let canDel = false
        // // 当前登录用户可删除同属一个机构下的其它用户
        // const currentOrgId = this.getUser.orgId
        // const currentRowOrgId = row.orgId
        // const parentList = (getParentsById(this.orgTree, currentRowOrgId, 'key') || [])
        //   .map(i => i.key)
        //   .reverse()
        // if (parentList.includes(currentOrgId) || this.getUser.userId === 'admin') {
        //   canDel = true
        // } else {
        //   canDel = false
        // }
        // // 默认账号不允许删除
        // if (window.__config__.defaultAccount.includes(row.userId.toLowerCase())) {
        //   canDel = this.getUser.userId === 'admin'
        // }
        const canDel = !window.__config__.defaultAccount.includes(row.userId.toLowerCase())

        return (
          this.permission.del &&
          row.userId !== 'admin' &&
          row.userId !== this.getUser.userId &&
          canDel
        )
      }
    }
  }
</script>

<style scoped></style>
